﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Web.UI.WebControls;
using Mang24k99.Model.COMM;
using System.Data;
using Castle.ActiveRecord;
using Castle.ActiveRecord.Queries;
using System.Reflection;
using NHibernate.Expression;
using System.Web.UI;

namespace Mang24k99.Business.COMM
{
    public class BTreeView:ActiveRecordBase
    {
        /// <summary>
        /// 建立一棵树
        /// </summary>
        /// <param name="tree"></param>
        public static void CreateTree(TreeView tree,int treeno)
        {
            SetTreeStyle(tree);
            TreeNode root = new TreeNode();
            DataTable dtRoot = ReadRootNode(treeno);
            if (dtRoot.Rows.Count>0)
            {
                root.ImageUrl = "~/Images/TreeViewImg/folder-closed.gif";
                root.Text = dtRoot.Rows[0]["text"].ToString();
                root.Value = dtRoot.Rows[0]["value"].ToString();
                root.ToolTip = dtRoot.Rows[0]["value"].ToString();
                root.SelectAction = TreeNodeSelectAction.Expand;
                tree.Nodes.Add(root);
            }
            //建立一级子节点
            CreateChileNode(treeno, root); 
        }

        private static void SetTreeStyle(TreeView tree)
        {
            //tree.ShowCheckBoxes = TreeNodeTypes.All;
            tree.ShowLines = true;
            tree.ShowExpandCollapse = true;
            tree.RootNodeStyle.ImageUrl = "~/Images/TreeViewImg/folder-closed.gif";
            tree.ParentNodeStyle.ImageUrl = "~/Images/TreeViewImg/folder.gif";
            tree.LeafNodeStyle.ImageUrl = "~/Images/TreeViewImg/file.gif";
        }
        /// <summary>
        /// 根据树编号与父节点建立子节点
        /// </summary>
        /// <param name="treeno"></param>
        /// <param name="root"></param>
        public static void CreateChileNode(int treeno, TreeNode root)
        {
            if (root.Value!="")
            {
                int nodevalue = Convert.ToInt32(root.Value);
                DataTable dtChild = ReadChild(treeno, nodevalue);
                for (int i = 0; i < dtChild.Rows.Count; i++)
                {
                    TreeNode childnode = new TreeNode();
                    childnode.Text = dtChild.Rows[i]["text"].ToString();
                    childnode.Value = dtChild.Rows[i]["value"].ToString();
                    childnode.ToolTip = dtChild.Rows[i]["value"].ToString();
                    DataTable dt = ReadChild(treeno, Convert.ToInt32(childnode.Value));
                    if (dt.Rows.Count == 0)
                    {
                        childnode.SelectAction = TreeNodeSelectAction.SelectExpand;
                        childnode.ImageUrl = "~/Images/TreeViewImg/file.gif";
                    }
                    else
                    {
                        childnode.SelectAction = TreeNodeSelectAction.SelectExpand;
                        childnode.ImageUrl = "~/Images/TreeViewImg/folder.gif";
                    }
                    childnode.Expanded = true;
                    root.ChildNodes.Add(childnode);
                }
            }
           
        }
        /// <summary>
        /// 根据树编号读取根节点数据
        /// </summary>
        /// <param name="treeno"></param>
        /// <returns></returns>
        public static DataTable ReadRootNode(int treeno)
        {
            Mang24k99.Model.COMM.MKtCommTreeconfig config = Mang24k99.Business.COMM.BKtCommTreeconfig.Find(treeno);
            string tableName = config.TableName;
            string disfiledName = config.DisfiledName;
            string filednoName = config.FilednoName;

            Type obj = GetTableObj(tableName);
            object objValue = GetRootNode(obj, treeno, tableName);
            DataTable dt = GetNodeInfo(disfiledName, filednoName, objValue);

            return dt;
        }
        /// <summary>
        /// 根据树编号读取一级节点
        /// </summary>
        /// <param name="treeno"></param>
        /// <returns></returns>
        public static DataTable ReadLevelOneNode(int treeno)
        {
            Mang24k99.Model.COMM.MKtCommTreeconfig config = Mang24k99.Business.COMM.BKtCommTreeconfig.Find(treeno);
            string tableName = config.TableName;
            string disfiledName = config.DisfiledName;
            string filednoName = config.FilednoName;

            Type obj = GetTableObj(tableName);
            object objValue = GetLevelOneNode(obj, treeno, tableName);
            DataTable dt = GetNodeInfo(disfiledName, filednoName, objValue);

            return dt;
        }
        /// <summary>
        /// 根据树编号，父节点value读取孩子节点
        /// </summary>
        /// <param name="treeno"></param>
        /// <param name="nodeValue"></param>
        /// <returns></returns>
        public static DataTable ReadChild(int treeno,int nodeValue)
        {
            Mang24k99.Model.COMM.MKtCommTreeconfig config = Mang24k99.Business.COMM.BKtCommTreeconfig.Find(treeno);
            string tableName = config.TableName;
            string disfiledName = config.DisfiledName;
            string filednoName = config.FilednoName;

            Type obj = GetTableObj(tableName);
            object objValue = GetChildInfo(obj,treeno,tableName,nodeValue);
            DataTable dt = GetNodeInfo(disfiledName, filednoName, objValue);

            return dt;
        }

        private static DataTable GetNodeInfo(string disfiledName, string filednoName, object objValue)
        {
            Type t = objValue.GetType();
            MethodInfo mi = t.GetMethod("GetValue", new Type[] { typeof(int) });
            int ArrayLength = (int)t.GetProperty("Length").GetValue(objValue, null);

            DataTable dt = new DataTable();
            dt.Columns.Add("text", typeof(string));
            dt.Columns.Add("value", typeof(string));
            for (int i = 0; i < ArrayLength; i++)
            {
                object o = mi.Invoke(objValue, new object[] { i });
                object text = o.GetType().GetProperty(disfiledName).GetValue(o, null);
                object value = o.GetType().GetProperty(filednoName).GetValue(o, null);
                dt.Rows.Add(new object[] { text, value });
            }
            return dt;
        }
        /// <summary>
        /// 读取根节点信息
        /// </summary>
        /// <param name="obj">表对象</param>
        /// <param name="treeno">树结构编号</param>
        /// <param name="tableName">表名称</param>
        /// <returns></returns>
        public static object GetRootNode(Type obj,int treeno,string tableName)
        {
            string alias = "obj";//别名
            string where = ReadRootWhere(treeno, alias);
            string hql = @"from " + tableName + " " + alias + " " + where;
            SimpleQuery query = new SimpleQuery(obj, hql);
            try
            {
                return ExecuteQuery(query);
            }
            catch (System.Exception e)
            {
                return null;
            }
            
        }
        /// <summary>
        /// 读取一级节点信息
        /// </summary>
        /// <param name="obj">表对象</param>
        /// <param name="treeno">树结构编号</param>
        /// <param name="tableName">表名称</param>
        /// <returns></returns>
        public static object GetLevelOneNode(Type obj, int treeno, string tableName)
        {
            string alias = "obj";//别名
            string where = ReadLevelOneWhere(treeno, alias);
            string hql = @"from " + tableName + " " + alias + " " + where;
            SimpleQuery query = new SimpleQuery(obj, hql);
            return ExecuteQuery(query);
        }
        /// <summary>
        /// 读取孩子节点信息
        /// </summary>
        /// <param name="obj">表对象</param>
        /// <param name="treeno">树编号</param>
        /// <param name="tableName">表名称</param>
        /// <param name="rootValue">根节点value值</param>
        /// <returns></returns>
        public static object GetChildInfo(Type obj,int treeno,string tableName,int rootValue)
        {
            string alias = "obj";//别名
            string where = "";
            //读取配置值condtype=2
            ICriterion[] criteria = new ICriterion[]
            {
                Expression.Eq("MKtCommTreeconfig.TreeNO",treeno),
                Expression.Eq("CondType",2)
            };
            IList<Mang24k99.Model.COMM.MKtCommTreecondition> cond = Mang24k99.Model.COMM.MKtCommTreecondition.SelectAll(criteria);
            if (cond.Count<=0)
            {
                return null;
            }
            for (int i = 0; i < cond.Count;i++ )
            {
                if (i == 0)
                {
                    where += " where " + alias + "." + cond[i].FieldName + " " + cond[i].FieldValue;
                }
                else
                {
                    where += " and " + alias + "." + cond[i].FieldName + " " + cond[i].FieldValue;
                }
            }
            //读取传入参数 condtype=1
            ICriterion[] criterion = new ICriterion[]
            {
                Expression.Eq("MKtCommTreeconfig.TreeNO",treeno),
                Expression.Eq("CondType",1)
            };
            IList<Mang24k99.Model.COMM.MKtCommTreecondition> condition = Mang24k99.Model.COMM.MKtCommTreecondition.SelectAll(criterion);
            if (condition.Count>0)
            {
                where += " and " + alias + "." + condition[0].FieldName + "=" + rootValue;
            }
            string hql = @"from " + tableName + " " + alias + " " + where;
            SimpleQuery query = new SimpleQuery(obj, hql);
            try
            {
                return ExecuteQuery(query);
            }
            catch (System.Exception e)
            {
                return null;
            }
            
        }
        /// <summary>
        /// 通过对象名字符串获取对象
        /// </summary>
        /// <param name="tablename"></param>
        /// <returns></returns>
        public static Type GetTableObj(string tablename)
        {
            Assembly a = Assembly.Load("Mang24k99.Model");
            Type[] objarray = a.GetTypes();
            Type o = null;
            foreach (Type obj in objarray)
            {
                if (obj.FullName == tablename)
                {
                    o = obj;
                }
            }
            return o;
        }
        public static string ReadRootWhere(int treeno,string alias)
        {
            string where = "";
            Mang24k99.Model.COMM.MKtCommTreeconfig config = Mang24k99.Business.COMM.BKtCommTreeconfig.Find(treeno);
            string filednoName = config.FilednoName;
            //读取传入参数 condtype=1
            ICriterion[] criterion = new ICriterion[]
            {
                Expression.Eq("MKtCommTreeconfig.TreeNO",treeno),
                Expression.Eq("CondType",1)
            };
            IList<Mang24k99.Model.COMM.MKtCommTreecondition> condition = Mang24k99.Model.COMM.MKtCommTreecondition.SelectAll(criterion);
            if (condition.Count<=0)
            {
                return where;
            }
            where = " where " + alias + "." + filednoName + " " + condition[0].FieldValue + "";
            return where;
        }
        /// <summary>
        /// 读取树型结构的一级节点条件配置信息(where条件)
        /// </summary>
        /// <param name="treeno">树结构编号</param>
        /// <param name="alias">对象别名</param>
        /// <returns></returns>
        public static string ReadLevelOneWhere(int treeno, string alias)
        {
            ICriterion[] criterion= new ICriterion[]
            {
                Expression.Eq("MKtCommTreeconfig.TreeNO",treeno),
            };
            IList<Mang24k99.Model.COMM.MKtCommTreecondition> condition = Mang24k99.Model.COMM.MKtCommTreecondition.SelectAll(criterion);
            string where = "";
            for (int i = 0; i < condition.Count; i++)
            {
                if (i == 0)
                {
                    where += " where " + alias + "." + condition[i].FieldName +" "+ condition[i].FieldValue;
                }
                else
                {
                    where += " and " + alias + "." + condition[i].FieldName + " "+condition[i].FieldValue;
                }
            }

            return where;
        }

        public static string GetMenu(int treeno)
        {
            IList<MKtCommTreemenu>  menu= BKtCommTreemenu.FindALLByProperty("MKtCommTreeconfig.TreeNO", treeno);
            StringBuilder stringBuilderReturn = new StringBuilder();
            stringBuilderReturn.Append("<ul>");
            for (int i = 0; i < menu.Count;i++ )
            {
                stringBuilderReturn.Append("<li id=\""+menu[i].DisplayName+"\">");
                string url = "";
                string img = "";
                if (menu[i].LinkAddr!="")
                {
                    url = "<a href=\"" + menu[i].LinkAddr + menu[i].LinkRef + "\">";
                }
                if (menu[i].MKtCommCodelist.CODE_NO == 312001)
                {
                    img = "<img src=\"TestImag/cross.png\" alt=\"\" />";
                }
                else if (menu[i].MKtCommCodelist.CODE_NO==312002)
                {
                    img = "<img src=\"TestImag/folder.png\" alt=\"\" />";
                }
                stringBuilderReturn.Append(""+img +url + menu[i].DisplayName + "</a></li>");
            }
            stringBuilderReturn.Append("</ul	>");
            return stringBuilderReturn.ToString();
        }
    }
}
